package gl.java.umsp.gateway;

import gl.java.umsp.Umsp;
import gl.java.umsp.UmspHeader;
import gl.java.umsp.protocol.*;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
@ChannelHandler.Sharable
@Slf4j
public class GateWayMessageDispatcher extends SimpleChannelInboundHandler<UmspHeader> {
    ArrayList<IUmspHandler> handleList = new ArrayList<IUmspHandler>();
    private static GateWayMessageDispatcher instance = new GateWayMessageDispatcher();
    public static GateWayMessageDispatcher getInstance(){
        return instance;
    };
    public GateWayMessageDispatcher(){
        handleList.add(new GateWayHandleRoomServiceLogin());
        handleList.add(new GateWayHandleHeartBeat());
        handleList.add(new GateWayHandleSendMessage());
        handleList.add(new GateWayHandleMatch());
        handleList.add(new GateWayHandleUserLogin());
        handleList.add(new GateWayHandleUserLogout());
        handleList.add(new GateWayHandleRoomEnter());
        handleList.add(new GateWayHandleRoomExit());
        handleList.add(new GateWayHandleRoomChanged());
        handleList.add(new GateWayHandleMsgRsp());
    }
	@Override
	public void channelRead0(ChannelHandlerContext ctx, UmspHeader msg)
			{
        if (msg.cmd!= Umsp.CMD_HEARTBEAT){
            log.info("dispatcher msg:"+ msg);
        }
        for (IUmspHandler iUmspHandler : handleList) {
            if(iUmspHandler.handle(ctx,msg)){
                return;
            }
        }
        log.warn("No handler to handle the msg:"+msg.toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }
}
